﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Navigation;
using System.IO.IsolatedStorage;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Tasks;

using GrimorioApplication.Localization;
using GrimorioApplication.Model;

namespace GrimorioApplication.Views
{
    public partial class EditRecipe : PhoneApplicationPage
    {
        string photoNameOfRecipe = "";
        int idOfRecipe;
        PhotoChooserTask photoChooserTask = new PhotoChooserTask();

        public EditRecipe()
        {
            InitializeComponent();
            ApplicationBarInitializer();
            this.photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_completed);

            recipeDishListPicker.ItemsSource = new List<string> { 
                GrimorioLang.listpicker_dish_antipasto, 
                GrimorioLang.listpicker_dish_primo,
                GrimorioLang.listpicker_dish_secondo,
                GrimorioLang.listpicker_dish_contorno,
                GrimorioLang.listpicker_dish_dolce };

            recipeDifficultyListPicker.ItemsSource = new List<string>
            {
                GrimorioLang.listpicker_difficulty_easy,
                GrimorioLang.listpicker_difficulty_medium,
                GrimorioLang.listpicker_difficulty_hard };
        }

        private void ApplicationBarInitializer()
        {
            ApplicationBar = new ApplicationBar();
            ApplicationBar.Mode = ApplicationBarMode.Default;
            ApplicationBar.Opacity = 1.0;
            ApplicationBar.IsVisible = true;
            ApplicationBar.IsMenuEnabled = false;

            // save button
            ApplicationBarIconButton btn_save = new ApplicationBarIconButton();
            btn_save.IconUri = new Uri("/Img/appbar_save.png", UriKind.Relative);
            btn_save.Text = GrimorioLang.save;
            ApplicationBar.Buttons.Add(btn_save);
            btn_save.Click += new EventHandler(btn_save_Click);

            // undo button
            ApplicationBarIconButton btn_undo = new ApplicationBarIconButton();
            btn_undo.IconUri = new Uri("/Img/appbar_cancel.png", UriKind.Relative);
            btn_undo.Text = GrimorioLang.undo;
            ApplicationBar.Buttons.Add(btn_undo);
            btn_undo.Click += new EventHandler(btn_undo_Click);
        }

        private void btn_undo_Click(object sender, EventArgs e)
        {
            NavigationService.GoBack();
        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            DataRecipe recipeToEdit = App.ViewModel.getRecipeWithSelectedId(idOfRecipe);

            if (recipeName.Text == "")
                MessageBox.Show(GrimorioLang.messagebox_nameRequired, GrimorioLang.messagebox_warning, MessageBoxButton.OK);
            else
            {
                bool sameName = false;
                foreach (DataRecipe dr in App.ViewModel.AllRecipes)
                    if (recipeName.Text.ToLower() == dr.RecipeName.ToLower())
                        sameName = true;
                if (recipeName.Text == recipeToEdit.RecipeName)
                    sameName = false;
                if (sameName)
                    MessageBox.Show(GrimorioLang.messagebox_nameRequired, GrimorioLang.messagebox_warning, MessageBoxButton.OK);
                else
                {
                    recipeToEdit.RecipeName = recipeName.Text;
                    if (ratingStars.Value != 0.0)
                        recipeToEdit.Rating = ratingStars.Value;
                    if (recipeNumberOfPeople.Text != "")
                        recipeToEdit.NumberOfPeople = Convert.ToInt16(recipeNumberOfPeople.Text);
                    recipeToEdit.IsVegetarian = (bool)reciepVegetarian.IsChecked;
                    recipeToEdit.Difficulty = (string)recipeDifficultyListPicker.SelectedItem;
                    recipeToEdit.TimeForPreparation = recipeTime.Text;
                    recipeToEdit.Description = recipeBreifDescription.Text;
                    recipeToEdit.Matchings = recipeMatchings.Text;
                    recipeToEdit.Preparation = recipePreparation.Text;
                    recipeToEdit.Image = photoNameOfRecipe;
                    recipeToEdit.Dish = (string)recipeDishListPicker.SelectedItem;

                    NavigationService.GoBack();
                }
            }
        }

        public void ReadAllData()
        {
            ReadIngredientsData();
            ReadRecipeData();
        }

        public void ReadRecipeData()
        {
            DataRecipe recipeToRead = App.ViewModel.getRecipeWithSelectedId(idOfRecipe);
            recipeName.Text = recipeToRead.RecipeName;
            ratingStars.Value = (double)recipeToRead.Rating;
            recipeBreifDescription.Text = recipeToRead.Description;
            recipeNumberOfPeople.Text = recipeToRead.NumberOfPeople.ToString();
            recipeDishListPicker.SelectedItem = recipeToRead.Dish;
            reciepVegetarian.IsChecked = recipeToRead.IsVegetarian;
            recipeDifficultyListPicker.SelectedItem = recipeToRead.Difficulty;
            recipeTime.Text = recipeToRead.TimeForPreparation;
            recipeMatchings.Text = recipeToRead.Matchings;
            recipePreparation.Text = recipeToRead.Preparation;

            if (recipeToRead.Image != "")
            {
                // Ricostruisco l'immagine prelevando lo stream dall'isostore (Dicono sia più veloce che non l'usare i byte[])
                BitmapImage bi = new BitmapImage();
                using (IsolatedStorageFile myIsoStore = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (IsolatedStorageFileStream imageFileStream = myIsoStore.OpenFile("/RecipePhotos/" + recipeToRead.Image, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                    {
                        bi.SetSource(imageFileStream);
                    }
                    recipePhoto.Source = bi;
                }
            }

        }
        public void ReadIngredientsData()
        {
            List<GrimorioApplication.ViewModel.IngredientsAndQuantity> ingredientsAndQuantity = App.ViewModel.getIngredientsAndQuantityOfRecipeSelected(idOfRecipe);
            IgredientsList.ItemsSource = ingredientsAndQuantity;
        }

        // Caricamento della lista quando viene caricata la pagina.
        private void PivotItem_Loaded(object sender, RoutedEventArgs e)
        {
            List<GrimorioApplication.ViewModel.IngredientsAndQuantity> listOfIngredientsAndQuantity = App.ViewModel.getIngredientsAndQuantityOfRecipeSelected(idOfRecipe);
            IgredientsList.ItemsSource = listOfIngredientsAndQuantity;
        }

        // Tap per far partire il task
        private void recipePhoto_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
        {
            photoChooserTask.PixelHeight = 300;
            photoChooserTask.PixelWidth = 400;
            photoChooserTask.Show();
        }

        // Completo il task: la foto è prima fatta visualizzare al posto del segnaposto, poi salvata tramite stream nell'isostore.
        public void photoChooserTask_completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                BitmapImage image = new BitmapImage();
                image.SetSource(e.ChosenPhoto);
                recipePhoto.Source = image;
                DateTime now = DateTime.Now;
                photoNameOfRecipe = now.Millisecond.ToString() + now.Hour.ToString() + now.Minute.ToString() + now.Second.ToString();

                WriteableBitmap writeableImage = new WriteableBitmap(image);

                using (IsolatedStorageFile myIsoStore = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (!myIsoStore.DirectoryExists("RecipePhotos"))
                        myIsoStore.CreateDirectory("RecipePhotos");
                    IsolatedStorageFileStream fileStream = myIsoStore.CreateFile("/RecipePhotos/" + photoNameOfRecipe);
                    Extensions.SaveJpeg(writeableImage, fileStream, writeableImage.PixelWidth, writeableImage.PixelHeight, 0, 100);
                    fileStream.Close();
                }
            }
        }

        private void AddQIng_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/EditQIng.xaml?" + "ID=" + idOfRecipe, UriKind.Relative));
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string ID;
            if (NavigationContext.QueryString.TryGetValue("ID", out ID))
                idOfRecipe = Convert.ToInt32(ID);
            ReadAllData();
            base.OnNavigatedTo(e);
        }

        private void DeleteIngredientFromList(object sender, System.Windows.Input.GestureEventArgs e)
        {
            // Prendo il nome dell'ingrediente.
            // dal nome risalgo all'id
            // Elimino la referenza se RecipeIngredient è uguale a recipe withdefaultname && idOfingredient
            List<RecipeIngredients> myList = App.ViewModel.recipeIngredientsOfSelectedRecipe(idOfRecipe);
            GrimorioApplication.ViewModel.IngredientsAndQuantity toBeDel = (GrimorioApplication.ViewModel.IngredientsAndQuantity)IgredientsList.SelectedItem;

            foreach (RecipeIngredients item in myList)
            {
                if (item.Ingredient.IngredientName == toBeDel.ingredientName)
                {
                    App.ViewModel.DeleteRecipeToIng(item);
                }
            }

            // Reload list
            List<GrimorioApplication.ViewModel.IngredientsAndQuantity> listOfIngredientsAndQuantity = App.ViewModel.getIngredientsAndQuantityOfRecipeSelected(idOfRecipe);

            IgredientsList.ItemsSource = listOfIngredientsAndQuantity;

        }
    }
}